/**
 * Admin Store
 * 负责管理admin相关的状态和数据处理
 */

import { observable, action, runInAction  } from 'mobx-miniprogram';
import cloudHelper from '../../../helpers/cloud_helper.js';
import PublicBiz from '../../../comm/biz/public_biz.js';
import AdminBiz from '../../../comm/biz/admin_biz.js';
import pageHelper from '../../../helpers/page_helper.js';
import constants from '../../../constants/constants.js';
import cacheHelper from '../../../helpers/cache_helper.js';

// 管理员模块Store
export const adminStore = observable({
  // 系统设置
  systemSettings: {
    name: '',
    logo: '',
    adminContact: '',
    announcement: '',
    version: '',
    about: '',
    mainColor: '#0066cc',
    subColor: '#0099ff'
  },
  
  // 设置内容项
  setupContentItems: [],
  
  // 用户管理数据
  userList: [],
  
  // 角色列表
  roleList: [],
  
  // 权限列表
  permissionList: [],
  
  // 角色权限映射
  rolePermissions: {},
  
  // 当前选中的用户
  currentUser: null,
  
  // 用户过滤条件
  userFilter: {
    role: '',
    status: '',
    searchKey: '',
    department: '',
    sortBy: 'createTime',
    sortOrder: 'desc'
  },
  
  // 操作日志列表
  operationLogs: [],
  
  // 日志过滤条件
  logFilter: {
    type: '',
    user: '',
    startDate: null,
    endDate: null,
    searchKey: ''
  },
  
  // 部门列表
  departments: [],
  
  // 统计数据
  statistics: {
    totalUsers: 0,
    activeUsers: 0,
    adminUsers: 0,
    todayLogins: 0,
    byRole: {},
    byDepartment: {}
  },
  
  // 缓存管理状态
  cache: {
    userCacheSize: 0,
    systemCacheSize: 0,
    lastClearTime: null
  },
  
  // 页面加载状态
  loading: {
    users: false,
    settings: false,
    logs: false,
    roles: false,
    home: false,
    news: false,
    mgr: false
  },
  
  // 计算属性：筛选后的用户列表
  get filteredUsers() {
    if (!this.userList.length) return [];
    
    let filtered = [...this.userList];
    
    // 根据角色筛选
    if (this.userFilter.role) {
      filtered = filtered.filter(u => u.role === this.userFilter.role);
    }
    
    // 根据状态筛选
    if (this.userFilter.status) {
      filtered = filtered.filter(u => u.status === this.userFilter.status);
    }
    
    // 根据部门筛选
    if (this.userFilter.department) {
      filtered = filtered.filter(u => u.department === this.userFilter.department);
    }
    
    // 根据关键词搜索
    if (this.userFilter.searchKey) {
      const key = this.userFilter.searchKey.toLowerCase();
      filtered = filtered.filter(u => 
        u.name.toLowerCase().includes(key) || 
        u.nickName.toLowerCase().includes(key) ||
        u.phone.includes(key) ||
        u.email.toLowerCase().includes(key)
      );
    }
    
    // 排序
    filtered.sort((a, b) => {
      const field = this.userFilter.sortBy;
      const order = this.userFilter.sortOrder === 'asc' ? 1 : -1;
      
      if (field === 'createTime' || field === 'lastLoginTime') {
        const dateA = dayjs(a[field] || 0);
        const dateB = dayjs(b[field] || 0);
        return dateA > dateB ? order : -order;
      }
      
      return a[field] > b[field] ? order : -order;
    });
    
    return filtered;
  },
  
  // 计算属性：筛选后的操作日志
  get filteredLogs() {
    if (!this.operationLogs.length) return [];
    
    let filtered = [...this.operationLogs];
    
    // 根据类型筛选
    if (this.logFilter.type) {
      filtered = filtered.filter(log => log.type === this.logFilter.type);
    }
    
    // 根据用户筛选
    if (this.logFilter.user) {
      filtered = filtered.filter(log => log.userId === this.logFilter.user);
    }
    
    // 根据日期范围筛选
    if (this.logFilter.startDate && this.logFilter.endDate) {
      const startDate = dayjs(this.logFilter.startDate);
      const endDate = dayjs(this.logFilter.endDate);
      endDate.setHours(23, 59, 59, 999); // 设置为当天结束时间
      
      filtered = filtered.filter(log => {
        const createTime = dayjs(log.createTime);
        return createTime >= startDate && createTime <= endDate;
      });
    }
    
    // 根据关键词搜索
    if (this.logFilter.searchKey) {
      const key = this.logFilter.searchKey.toLowerCase();
      filtered = filtered.filter(log => 
        log.content.toLowerCase().includes(key) || 
        log.module.toLowerCase().includes(key) ||
        log.userName.toLowerCase().includes(key)
      );
    }
    
    // 按时间倒序排序
    filtered.sort((a, b) => dayjs(b.createTime) - dayjs(a.createTime));
    
    return filtered;
  },
  
  // 计算属性：获取管理员用户列表
  get adminUsers() {
    return this.userList.filter(u => 
      u.role === 'admin' || 
      u.role === 'superAdmin'
    );
  },
  
  // Action: 设置系统设置
  setSystemSettings: action(function(settings) {
    this.systemSettings = {...this.systemSettings, ...settings};
  }),
  
  // Action: 设置设置内容项列表
  setSetupContentItems: action(function(items) {
    this.setupContentItems = items;
  }),
  
  // Action: 设置用户列表
  setUserList: action(function(users) {
    this.userList = users;
    this.updateStatistics();
  }),
  
  // Action: 设置角色列表
  setRoleList: action(function(roles) {
    this.roleList = roles;
  }),
  
  // Action: 设置权限列表
  setPermissionList: action(function(permissions) {
    this.permissionList = permissions;
  }),
  
  // Action: 设置角色权限映射
  setRolePermissions: action(function(rolePermissions) {
    this.rolePermissions = rolePermissions;
  }),
  
  // Action: 设置操作日志列表
  setOperationLogs: action(function(logs) {
    this.operationLogs = logs;
  }),
  
  // Action: 设置部门列表
  setDepartments: action(function(departments) {
    this.departments = departments;
  }),
  
  // Action: 更新统计数据
  updateStatistics: action(function() {
    const now = dayjs();
    now.setHours(0, 0, 0, 0);
    
    // 按角色统计
    const byRole = {};
    this.roleList.forEach(role => {
      byRole[role.id] = this.userList.filter(u => u.role === role.id).length;
    });
    
    // 按部门统计
    const byDepartment = {};
    this.departments.forEach(dept => {
      byDepartment[dept.id] = this.userList.filter(u => u.department === dept.id).length;
    });
    
    // 统计今日登录用户
    const todayLogins = this.userList.filter(u => {
      if (!u.lastLoginTime) return false;
      const loginTime = dayjs(u.lastLoginTime);
      return loginTime >= now;
    }).length;
    
    this.statistics = {
      totalUsers: this.userList.length,
      activeUsers: this.userList.filter(u => u.status === 'active').length,
      adminUsers: this.userList.filter(u => u.role === 'admin' || u.role === 'superAdmin').length,
      todayLogins,
      byRole,
      byDepartment
    };
  }),
  
  // Action: 设置当前用户
  setCurrentUser: action(function(userId) {
    this.currentUser = this.userList.find(u => u._id === userId) || null;
  }),
  
  // Action: 添加用户
  addUser: action(function(user) {
    this.userList.push(user);
    this.updateStatistics();
  }),
  
  // Action: 更新用户
  updateUser: action(function(userId, data) {
    const index = this.userList.findIndex(u => u._id === userId);
    if (index >= 0) {
      this.userList[index] = {...this.userList[index], ...data};
      
      // 如果当前选中的是这个用户，也更新currentUser
      if (this.currentUser && this.currentUser._id === userId) {
        this.currentUser = {...this.currentUser, ...data};
      }
      
      this.updateStatistics();
    }
  }),
  
  // Action: 删除用户
  deleteUser: action(async function(id) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    const pageHelper = require('../../../helpers/page_helper.js');
    
    try {
      let params = { id };
      let opts = {
        title: '删除中'
      }
      await cloudHelper.callCloudSumbit('admin/user_del', params, opts);
      
      // 从列表中移除
      const index = this.userList.findIndex(u => u.USER_MINI_OPENID === id);
      if (index > -1) {
        this.userList.splice(index, 1);
      }
      
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]删除用户失败', err);
      return false;
    }
  }),
  
  // Action: 设置用户权限
  setUserPermissions: action(function(userId, permissions) {
    const index = this.userList.findIndex(u => u._id === userId);
    if (index >= 0) {
      this.userList[index].permissions = permissions;
      
      // 如果当前选中的是这个用户，也更新currentUser
      if (this.currentUser && this.currentUser._id === userId) {
        this.currentUser.permissions = permissions;
      }
    }
  }),
  
  // Action: 添加操作日志
  addOperationLog: action(function(log) {
    this.operationLogs.unshift(log);
    
    // 最多保留1000条记录
    if (this.operationLogs.length > 1000) {
      this.operationLogs.pop();
    }
  }),
  
  // Action: 清空操作日志
  clearOperationLogs: action(function() {
    this.operationLogs = [];
  }),
  
  // Action: 设置缓存信息
  setCacheInfo: action(function(cacheInfo) {
    this.cache = {...this.cache, ...cacheInfo};
  }),
  
  // Action: 清除缓存
  clearCache: action(function(type) {
    if (type === 'user' || type === 'all') {
      this.cache.userCacheSize = 0;
    }
    
    if (type === 'system' || type === 'all') {
      this.cache.systemCacheSize = 0;
    }
    
    this.cache.lastClearTime = dayjs();
  }),
  
  // Action: 设置用户过滤条件
  setUserFilter: action(function(filter) {
    this.userFilter = {...this.userFilter, ...filter};
  }),
  
  // Action: 清空用户过滤条件
  clearUserFilter: action(function() {
    this.userFilter = {
      role: '',
      status: '',
      searchKey: '',
      department: '',
      sortBy: 'createTime',
      sortOrder: 'desc'
    };
  }),
  
  // Action: 设置日志过滤条件
  setLogFilter: action(function(filter) {
    this.logFilter = {...this.logFilter, ...filter};
  }),
  
  // Action: 清空日志过滤条件
  clearLogFilter: action(function() {
    this.logFilter = {
      type: '',
      user: '',
      startDate: null,
      endDate: null,
      searchKey: ''
    };
  }),
  
  // Action: 设置加载状态
  setLoading: action(function(key, isLoading) {
    if (this.loading[key] !== undefined) {
      this.loading[key] = isLoading;
    }
  }),
  
  // Action: 管理员登录
  adminLogin: action(async function(name, pwd) {
    try {
      if (name.length < 5 || name.length > 30) {
        wx.showToast({
          title: '账号输入错误(5-30位)',
          icon: 'none'
        });
        return false;
      }

      if (pwd.length < 5 || pwd.length > 30) {
        wx.showToast({
          title: '密码输入错误(5-30位)',
          icon: 'none'
        });
        return false;
      }
      
      let params = {
        name,
        pwd
      };
      
      let opt = {
        title: '登录中'
      };
      
      let res = await cloudHelper.callCloudSumbit('admin/login', params, opt);
      
      if (res && res.data && res.data.name) {
        // 存储管理员信息
        cacheHelper.set(constants.CACHE_ADMIN, res.data, constants.ADMIN_TOKEN_EXPIRE);
        return true;
      } else {
        return false;
      }
    } catch (err) {
      console.error('[MobX AdminStore]登录失败', err);
      return false;
    }
  }),
  
  // Action: 管理员退出
  adminLogout: action(function() {
    AdminBiz.clearAdminToken();
  }),
  
  // Action: 获取管理员Token
  getAdminToken: action(function() {
    return AdminBiz.getAdminToken();
  }),
  
  // Action: 检查是否为管理员
  isAdmin: action(function(that, isSuper = false) {
    return AdminBiz.isAdmin(that, isSuper);
  }),
  
  // Action: 加载管理首页数据
  loadHomeData: action(async function() {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    this.loading.home = true;
    
    try {
      let opts = {
        title: 'bar'
      }
      let res = await cloudHelper.callCloudData('admin/home', {}, opts);
      
      // 修复MobX严格模式错误 - 使用runInAction
      if (res) {
        runInAction(() => {
          this.statistics = {...this.statistics, ...res};
        });
      }
      
      this.loading.home = false;
      return res;
    } catch (err) {
      console.error('[MobX AdminStore]加载首页数据失败', err);
      this.loading.home = false;
      return null;
    }
  }),
  
  // Action: 清除推荐
  clearVouch: action(async function() {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    const pageHelper = require('../../../helpers/page_helper.js');
    
    try {
      await cloudHelper.callCloudSumbit('admin/clear_vouch');
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]清除推荐失败', err);
      return false;
    }
  }),
  
  // Action: 加载用户列表数据
  loadUserList: action(async function(params = {}) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    this.loading.users = true;
    
    try {
      let opts = {
        title: 'bar'
      }
      let res = await cloudHelper.callCloudData('admin/user_list', params, opts);
      if (res && res.list) {
        this.userList = res.list;
        return res;
      }
      this.loading.users = false;
      return null;
    } catch (err) {
      console.error('[MobX AdminStore]加载用户列表失败', err);
      this.loading.users = false;
      return null;
    }
  }),
  
  // Action: 修改用户状态
  updateUserStatus: action(async function(id, status, reason = '') {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let params = {
        id,
        status,
        reason
      };
      
      await cloudHelper.callCloudSumbit('admin/user_status', params);
      
      // 更新列表中的状态
      const index = this.userList.findIndex(u => u.USER_MINI_OPENID === id);
      if (index > -1) {
        this.userList[index].USER_STATUS = status;
        this.userList[index].USER_CHECK_REASON = reason;
      }
      
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]更新用户状态失败', err);
      return false;
    }
  }),
  
  // Action: 获取用户详情
  getUserDetail: action(async function(id) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let params = { id };
      let opts = {
        hint: false
      }
      let res = await cloudHelper.callCloudData('admin/user_detail', params, opts);
      
      if (res) {
        // 更新当前用户
        this.currentUser = res;
      }
      
      return res;
    } catch (err) {
      console.error('[MobX AdminStore]获取用户详情失败', err);
      return null;
    }
  }),
  
  // Action: 编辑用户
  editUser: action(async function(data) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let opts = {
        title: '提交中'
      }
      await cloudHelper.callCloudSumbit('admin/user_edit', data, opts);
      
      // 更新列表中的用户信息
      if (this.userList.length > 0) {
        const index = this.userList.findIndex(u => u.USER_MINI_OPENID === data.id);
        if (index > -1) {
          this.userList[index].USER_NAME = data.name;
          this.userList[index].USER_MOBILE = data.mobile;
          this.userList[index].USER_DEPT = data.dept;
          this.userList[index].USER_AUTH = data.auth;
        }
      }
      
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]编辑用户失败', err);
      return false;
    }
  }),
  
  // Action: 获取公告列表
  loadNewsList: action(async function(params = {}) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    this.loading.news = true;
    
    try {
      let opts = {
        title: 'bar'
      }
      let res = await cloudHelper.callCloudData('admin/news_list', params, opts);
      this.loading.news = false;
      return res;
    } catch (err) {
      console.error('[MobX AdminStore]加载公告列表失败', err);
      this.loading.news = false;
      return null;
    }
  }),
  
  // Action: 获取公告详情
  getNewsDetail: action(async function(id) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let params = { id };
      let opts = {
        title: 'bar'
      };
      return await cloudHelper.callCloudData('admin/news_detail', params, opts);
    } catch (err) {
      console.error('[MobX AdminStore]获取公告详情失败', err);
      return null;
    }
  }),
  
  // Action: 删除公告
  deleteNews: action(async function(id) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let params = { id };
      let opts = {
        title: '删除中'
      }
      await cloudHelper.callCloudSumbit('admin/news_del', params, opts);
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]删除公告失败', err);
      return false;
    }
  }),
  
  // Action: 更新公告排序
  updateNewsSort: action(async function(id, sort) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let params = { id, sort };
      await cloudHelper.callCloudSumbit('admin/news_sort', params);
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]更新公告排序失败', err);
      return false;
    }
  }),
  
  // Action: 更新公告推荐状态
  updateNewsVouch: action(async function(id, vouch) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let params = { id, vouch };
      await cloudHelper.callCloudSumbit('admin/news_vouch', params);
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]更新公告推荐状态失败', err);
      return false;
    }
  }),
  
  // Action: 更新公告状态
  updateNewsStatus: action(async function(id, status) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let params = { id, status };
      await cloudHelper.callCloudSumbit('admin/news_status', params);
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]更新公告状态失败', err);
      return false;
    }
  }),
  
  // Action: 编辑公告
  editNews: action(async function(data) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      await cloudHelper.callCloudSumbit('admin/news_edit', data);
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]编辑公告失败', err);
      return false;
    }
  }),
  
  // Action: 更新公告图片
  updateNewsPic: action(async function(imgList, newsId) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      await cloudHelper.transCoverTempPics(imgList, 'news/', newsId, 'admin/news_update_pic');
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]更新公告图片失败', err);
      return false;
    }
  }),
  
  // Action: 更新公告内容
  updateNewsContent: action(async function(content, newsId) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let updatedContent = await cloudHelper.transRichEditorTempPics(content, 'news/', newsId, 'admin/news_update_content');
      return updatedContent;
    } catch (err) {
      console.error('[MobX AdminStore]更新公告内容失败', err);
      return null;
    }
  }),
  
  // Action: 更新公告表单
  updateNewsForms: action(async function(forms, newsId) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      await cloudHelper.transFormsTempPics(forms, 'news/', newsId, 'admin/news_update_forms');
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]更新公告表单失败', err);
      return false;
    }
  }),
  
  // Action: 获取系统设置内容
  getSetupContent: action(async function(key) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    const pageHelper = require('../../../helpers/page_helper.js');
    
    try {
      let params = { key };
      let opts = { title: 'bar', hint: false };
      
      // 尝试从home/setup_get获取内容
      try {
        let res = await cloudHelper.callCloudSumbit('home/setup_get', params, opts);
        if (res && res.data) {
          return res.data;
        }
      } catch (homeErr) {
        console.warn('[MobX AdminStore]通过home/setup_get获取系统设置内容失败', homeErr);
      }
      
      // 如果home/setup_get失败，尝试从admin/setup_get获取
      try {
        let res = await cloudHelper.callCloudSumbit('admin/setup_get', params, opts);
        if (res && res.data) {
          return res.data;
        }
      } catch (adminErr) {
        console.warn('[MobX AdminStore]通过admin/setup_get获取系统设置内容失败', adminErr);
      }

      // 如果两种方式都失败，提供一个空的默认数据并给出提示
      console.warn(`[MobX AdminStore]无法获取设置内容: ${key}`);
      
      if (key.startsWith('SETUP_CONTENT_')) {
        // 对于富文本内容，返回一个空数组作为默认值
        pageHelper.showModal('获取系统设置内容失败，请重试', null, null, () => {});
        return [];
      } else {
        // 其他类型的设置返回null
        return null;
      }
    } catch (err) {
      console.error('[MobX AdminStore]获取系统设置内容失败', err);
      return [];
    }
  }),
  
  // Action: 设置系统内容
  setSetupContent: action(async function(formContent, key) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      await cloudHelper.transRichEditorTempPics(formContent, 'setup/', key, 'admin/setup_set_content');
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]设置系统内容失败', err);
      return false;
    }
  }),
  
  // Action: 获取小程序码
  getSetupQr: action(async function(path) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let params = { path };
      let opt = { title: 'bar' };
      let res = await cloudHelper.callCloudSumbit('admin/setup_qr', params, opt);
      if (res && res.data) {
        return res.data;
      }
      return null;
    } catch (err) {
      console.error('[MobX AdminStore]获取小程序码失败', err);
      return null;
    }
  }),
  
  // Action: 获取管理员列表
  loadMgrList: action(async function(params = {}) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    this.loading.mgr = true;
    
    try {
      let opts = { title: 'bar' };
      let res = await cloudHelper.callCloudData('admin/mgr_list', params, opts);
      this.loading.mgr = false;
      return res;
    } catch (err) {
      console.error('[MobX AdminStore]获取管理员列表失败', err);
      this.loading.mgr = false;
      return null;
    }
  }),
  
  // Action: 获取管理员详情
  getMgrDetail: action(async function(id) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let params = { id };
      let opts = { title: 'bar' };
      return await cloudHelper.callCloudData('admin/mgr_detail', params, opts);
    } catch (err) {
      console.error('[MobX AdminStore]获取管理员详情失败', err);
      return null;
    }
  }),
  
  // Action: 删除管理员
  deleteMgr: action(async function(id) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let params = { id };
      await cloudHelper.callCloudSumbit('admin/mgr_del', params);
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]删除管理员失败', err);
      return false;
    }
  }),
  
  // Action: 修改管理员状态
  updateMgrStatus: action(async function(id, status) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      let params = { id, status };
      await cloudHelper.callCloudSumbit('admin/mgr_status', params);
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]修改管理员状态失败', err);
      return false;
    }
  }),
  
  // Action: 修改管理员
  editMgr: action(async function(data) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      await cloudHelper.callCloudSumbit('admin/mgr_edit', data);
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]修改管理员失败', err);
      return false;
    }
  }),
  
  // Action: 修改管理员密码
  updateMgrPwd: action(async function(data) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    
    try {
      await cloudHelper.callCloudSumbit('admin/mgr_pwd', data);
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]修改管理员密码失败', err);
      throw err;
    }
  }),

  // 添加管理员
  insertMgr: action(async function(data) {
    try {
      await cloudHelper.callCloudSumbit('admin/mgr_insert', data);
      PublicBiz.removeCacheList('admin-mgr');
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]添加管理员失败', err);
      throw err;
    }
  }),
  
  // 获取管理员日志列表
  getLogList: action(async function(params) {
    try {
      let opts = { title: 'bar' };
      let res = await cloudHelper.callCloudData('admin/log_list', params, opts);
      return res;
    } catch (err) {
      console.error('[MobX AdminStore]获取管理员日志列表失败', err);
      return null;
    }
  }),
  
  // 清空管理员日志
  clearLog: action(async function() {
    try {
      await cloudHelper.callCloudSumbit('admin/log_clear');
      return true;
    } catch (err) {
      console.error('[MobX AdminStore]清空管理员日志失败', err);
      throw err;
    }
  }),
  
  // 获取流程数据文件信息
  getFlowData: action(async function(isDel) {
    try {
      let params = { isDel };
      let options = { title: 'bar' };
      let data = await cloudHelper.callCloudData('admin/flow_data_get', params, options);
      return data;
    } catch (err) {
      console.error('[MobX AdminStore]获取流程数据文件失败', err);
      return null;
    }
  }),
  
  // 导出流程数据
  exportFlowData: action(async function(params) {
    try {
      let options = { title: '数据生成中' };
      let res = await cloudHelper.callCloudData('admin/flow_data_export', params, options);
      return res;
    } catch (err) {
      console.error('[MobX AdminStore]导出流程数据失败', err);
      throw err;
    }
  }),
  
  // 删除流程数据文件
  deleteFlowData: action(async function() {
    try {
      let options = { title: '数据删除中' };
      let res = await cloudHelper.callCloudData('admin/flow_data_del', {}, options);
      return res;
    } catch (err) {
      console.error('[MobX AdminStore]删除流程数据文件失败', err);
      throw err;
    }
  })
});

// 下面是新添加的adminFlowStore
export const adminFlowStore = observable({
  // 流程列表数据
  flowList: [],
  
  // 总记录数
  total: 0,
  
  // 当前页码
  currentPage: 1,
  
  // 每页大小
  pageSize: 20,
  
  // 排序列表
  sortItems: [],
  
  // 排序菜单
  sortMenus: [],
  
  // 筛选条件
  filter: {
    search: '',
    sortType: '',
    sortVal: '',
    orderBy: 'createTime',
    orderDesc: 'desc',
    status: '',
    cateId: '',
    fields: '*'
  },
  
  // 页面加载状态
  isLoad: false,
  
  // 计算属性：当前列表页数据
  get dataList() {
    return {
      list: this.flowList,
      total: this.total,
      page: this.currentPage,
      size: this.pageSize
    };
  },
  
  // Action: 设置流程列表
  setFlowList: action(function(list, total) {
    this.flowList = list;
    this.total = total;
  }),
  
  // Action: 设置页面参数
  setPageParams: action(function(page, size) {
    this.currentPage = page || 1;
    this.pageSize = size || 20;
  }),
  
  // Action: 设置筛选条件
  setFilter: action(function(filter) {
    this.filter = {...this.filter, ...filter};
  }),
  
  // Action: 设置加载状态
  setLoading: action(function(isLoad) {
    this.isLoad = isLoad;
  }),
  
  // Action: 初始化搜索菜单
  initSearchMenu: action(function() {
    const FlowBiz = require('../../../helpers/flow_biz.js');
    
    let sortItems1 = FlowBiz.getCateMenu();
    
    let sortMenus = [
      { label: '全部', type: 'status', value: '' },
      { label: '审批中', type: 'status', value: '1' },
      { label: '已驳回', type: 'status', value: '8' },
      { label: '已完成', type: 'status', value: '9' }
    ];
    
    this.sortItems = [sortItems1];
    this.sortMenus = sortMenus;
  }),
  
  // Action: 加载流程列表数据
  loadFlowList: action(async function() {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    const pageHelper = require('../../../helpers/page_helper.js');
    
    try {
      this.setLoading(true);
      
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        search: this.filter.search || '',
        sortType: this.filter.sortType || '',
        sortVal: this.filter.sortVal || '',
        orderBy: this.filter.orderBy || 'createTime',
        orderDesc: this.filter.orderDesc || 'desc',
        status: this.filter.status || '',
        cateId: this.filter.cateId || '',
        fields: this.filter.fields || '*'
      };
      
      let options = {
        title: '加载中...'
      };
      
      const res = await cloudHelper.dataList('admin/flow_list', params, options);
      
      if (res && res.data) {
        this.setFlowList(res.data.list, res.data.total);
      }
      
      this.setLoading(false);
      return res;
    } catch (e) {
      console.error('加载流程列表失败:', e);
      this.setLoading(false);
      return null;
    }
  }),
  
  // Action: 删除流程
  deleteFlow: action(async function(id) {
    const cloudHelper = require('../../../helpers/cloud_helper.js');
    const pageHelper = require('../../../helpers/page_helper.js');
    
    if (!id) return false;
    
    try {
      let params = { id };
      
      let options = {
        title: '删除中'
      };
      
      let res = await cloudHelper.callCloudSumbit('admin/flow_del', params, options);
      
      if (res && res.data && res.data.success) {
        // 更新本地列表，移除已删除的流程
        const index = this.flowList.findIndex(item => item._id === id);
        if (index > -1) {
          this.flowList.splice(index, 1);
          this.total--;
        }
        
        pageHelper.showSuccToast('删除成功');
        return true;
      }
      
      return false;
    } catch (e) {
      console.error('删除流程失败:', e);
      return false;
    }
  })
}); 